{% extends "example_base.html" %}

{% block header_js %}
{{ block.super }}

<script src="https://js.stripe.com/v3/"></script>
{% endblock %}

{% block header_css %}
{{ block.super }}

<style>
    /**
     * The CSS shown here will not be introduced in the Quickstart guide, but shows
     * how you can use CSS to style your Element's container.
     */
    .StripeElement {
        box-sizing: border-box;

        height: 40px;

        padding: 10px 12px;

        border: 1px solid transparent;
        border-radius: 4px;
        background-color: white;

        box-shadow: 0 1px 3px 0 #e6ebf1;
        -webkit-transition: box-shadow 150ms ease;
        transition: box-shadow 150ms ease;
    }

    .StripeElement--focus {
        box-shadow: 0 1px 3px 0 #cfd7df;
    }

    .StripeElement--invalid {
        border-color: #fa755a;
    }

    .StripeElement--webkit-autofill {
        background-color: #fefde5 !important;
    }
</style>

{% endblock %}

{% block content %}
<section class="section">
    <div class="container">

        <h1 class="is-size-3">Example Payment Intent Manual Configuration</h1>

        <input id="cardholder-name" type="text" placeholder="Cardholder Name">
        <p class="form-row">
            <label for="card-element">
                Credit or debit card
            </label>
        <div id="card-element">
            <!-- A Stripe Element will be inserted here. -->
        </div>

        <!-- Used to display form errors. -->
        <div id="card-errors" role="alert"></div>
        <div id="card-success" role="alert">
            <span id="success-message"></span>
        </div>

        <button id="card-button">Submit Payment</button>

    </div>
</section>

<script>
    // Create a Stripe client.
    var stripe = Stripe('{{ STRIPE_PUBLIC_KEY }}');

    // Create an instance of Elements.
    var elements = stripe.elements();

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
        base: {
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    };

    // Create an instance of the card Element.
    var cardElement = elements.create('card', {style: style});
    cardElement.mount('#card-element');

    var cardholderName = document.getElementById('cardholder-name');
    var cardButton = document.getElementById('card-button');

    cardButton.addEventListener('click', function (ev) {
        stripe.createPaymentMethod('card', cardElement, {
            billing_details: {name: cardholderName.value}
        }).then(function (result) {
            if (result.error) {
                // Inform the user if there was an error.
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                // Otherwise send paymentMethod.id to your server.
                fetch("{% url 'djstripe_example:payment_intent' %}", {
                    method: 'POST',
                    headers: {
                        "X-CSRFToken": getCookie("csrftoken"),
                        "Accept": "application/json",
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest"
                    },
                    body: JSON.stringify({'payment_method_id': result.paymentMethod.id})
                }).then(function (result) {
                    // Handle server response.
                    result.json().then(function (json) {
                        handleServerResponse(json);
                    })
                });
            }
        });
    });

    function getCookie(name) {
        if (!document.cookie) {
            return null;
        }
        const xsrfCookies = document.cookie.split(';')
            .map(c => c.trim())
            .filter(c => c.startsWith(name + '='));
        if (xsrfCookies.length === 0) {
            return null;
        }
        return decodeURIComponent(xsrfCookies[0].split('=')[1]);
    }

    function handleServerResponse(response) {
        if (response.error) {
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = response.error;
        } else if (response.requires_action) {
            // Use Stripe.js to handle required card action
            stripe.handleCardAction(
                response.payment_intent_client_secret
            ).then(function (result) {
                if (result.error) {
                    // Show error in payment form
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    // The card action has been handled
                    // The PaymentIntent can be confirmed again on the server
                    fetch("{% url 'djstripe_example:payment_intent' %}", {
                        method: 'POST',
                        headers: {
                            "X-CSRFToken": getCookie("csrftoken"),
                            "Accept": "application/json",
                            "Content-Type": "application/json",
                            "X-Requested-With": "XMLHttpRequest"
                        },
                        body: JSON.stringify({payment_intent_id: result.paymentIntent.id})
                    }).then(function (confirmResult) {
                        confirmResult.json().then(function (json) {
                            handleServerResponse(json)
                        })
                    });
                }
            });
        } else {
            // Show success message
            document.getElementById('success-message').innerHTML = 'Success!!';
        }
    }

</script>

{% endblock %}
